<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006-2016 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: 流年 <liu21st@gmail.com>
// +----------------------------------------------------------------------

use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Reader\Xlsx;
use PhpOffice\PhpSpreadsheet\Reader\Xls;
use PhpOffice\PhpSpreadsheet\IOFactory;
//use PhpOffice\PhpSpreadsheet\Cell\Coordinate;
use PhpOffice\PhpSpreadsheet\Spreadsheet;
use PhpOffice\PhpSpreadsheet\Worksheet\PageSetup;
use PhpOffice\PhpSpreadsheet\Cell\DataType;
use PhpOffice\PhpSpreadsheet\Style\Fill;
use PhpOffice\PhpSpreadsheet\Style\Color;
use PhpOffice\PhpSpreadsheet\Style\Alignment;
use PhpOffice\PhpSpreadsheet\Style\Border;
use PhpOffice\PhpSpreadsheet\Style\NumberFormat;

/**
 * 查询方法
 * $table  string  表名
 * $type   int     查询类型   1=>多条查询，其他为单条查询
 * $data   array   参数
 *                 where  array   查询条件，根据tp5的多条件的数组
 *                 limit  int     查询条数
 *                 with   string   关联预载入的字符串,tp5的
 */
if (!function_exists('ysh_select')) {
    function ysh_select($table,$data = [],$type = 1)
    {
        if(!isset($data['where'])){
            $where = [];
        }else{
            $where = $data['where'];
        }
        if(!isset($data['limit'])){
            $limit = 20;
        }else{
            $limit = $data['limit'];
        }
        if(!isset($data['with'])){
            $with = [];
        }else{
            $with = $data['with'];
        }
        if($type == 1){
        	if($limit == 0){
            	$list = model($table)->where($where)->with($with)->select()->toArray();
            	return ['list'=>$list];
        	}else{
            	$list = model($table)->where($where)->with($with)->paginate($limit);
        	}
        }else{
            $list = model($table)->where($where)->with($with)->find();
        }
        if(!empty($list) && $type == 1){
            $page = $list->render();
            $list = $list->toArray();
            return ['list'=>$list,'page'=>$page];
        }elseif(!empty($list) && $type != 1){
            $list = $list->toArray();
            return ['list'=>$list];
        }else{
            return ['list'=>$list,'page'=>NULL];
        }
    }
}

/**
 * 修改方法
 * $table  string  表名
 * $data   array   修改的数据  如：['id'=>1,'name'=>'ysh']
 * $type   int     修改类型   1=>单一修改，其他为批量修改,默认为单条修改
 */
if (!function_exists('ysh_upload')) {
    function ysh_upload($table,$data,$type = 1)
    {
        if($type == 1){
            if(!isset($data['id'])){
                return '单一修改数据data中要有id';
            }
            $id = $data['id'];
            unset($data['id']);
            return model($table)->save($data,['id'=>$id]);
        }else{
            return model($table)->saveAll($data);
        }
    }
}
/**
 * 添加方法
 * $table  string  表名
 * $data   array   修改的数据  如：['id'=>1,'name'=>'ysh']
 * $type   int     修改类型   1=>单一添加，其他为批量添加，默认为单条添加
 */
if (!function_exists('ysh_save')) {
    function ysh_save($table,$data,$type = 1)
    {
        if($type == 1){
            return model($table)->save($data);
        }else{
            return model($table)->saveAll($data);
        }
    }
}

/**
 * 删除方法
 * $table  string  表名
 * $id     string  删除数据ID   如： '1,2,3'
 * $where  array   删除条件     如： ['id','>',10]
 */
if (!function_exists('ysh_delete')) {
    function ysh_delete($table,$id,$where = [])
    {
        if(count($where) != 3 && $where != []){
            return '删除条件不符合规范';
        }
        if($where){
            list($pk,$tj,$num) = $where;
            return model($table)->where($pk,$tj,$num)->delete();
        }else{
            return model($table)->destroy($id);
        }
    }
}


// 应用公共文件
function pr($var) {
        //if (Env::get('app_debug')) {
            if (function_exists('debug_backtrace')) {
                $debug = debug_backtrace(DEBUG_BACKTRACE_IGNORE_ARGS,1);
                if (isset($debug[0]['function']) && $debug[0]['function'] == 'pr') {
                    $template = PHP_SAPI !== 'cli' ? '<pre style="color:blue;">%s</pre>' : "\n%s\n";
                    printf($template, print_r('in ' . $debug[0]['file'] . " line " . $debug[0]['line'] . ' :', true));
                }
            }
            $template = PHP_SAPI !== 'cli' ? '<pre style="color:red;">%s</pre>' : "\n%s\n";
            printf($template, print_r($var, true));
       // }
}
function post()
{
	return array_filter(input('post.'));
}
function get()
{
	return array_filter(input('get.'));
}
//无线级
function getTree($data, $pId)
 {
      $tree = [];
  foreach($data as $k => $v)
      {
        if($v['pid'] == $pId){
             $v['pid'] = getTree($data, $v['id']);
             $tree[] = $v;
   }
 }
  return $tree;
 }
//无限极最高级直属
function pap($user,$pid){
    if($user['parent_id'] != 0){
        $parmen = app\admin\model\User::where('id','=',$user['parent_id'])->find();
        if($parmen){
            $parmen = $parmen->toArray();
            return pap($parmen, $parmen['parent_id']);
        }
    }
    return $user;
}

/**
 * 获取代理的所有下级id
 */
function getTeam($teamId,$tIds=[]){
    if(!empty($teamId)){
        $uidArray = [];
        foreach ($teamId AS $item){
            $array = model('user')->where('parent_id',$item)->column('id');
            if(empty($array)){
                continue;
            }
            $uidArray = array_merge($uidArray,$array);
        }
        $tIds = array_merge($tIds,$teamId,$uidArray);
       
        if(!empty($uidArray)){
            return getTeam($uidArray,$tIds);
        }
        
        return array_unique($tIds);
    }
    return $teamId;
}

function jfmx($num,$id,$jfid){
     
     $all =[];
     //产品兑换积分15
     $all[0]['num'] = round($num*0.15,2);
     $all[0]['status'] = 1;
     $all[0]['user_id'] = $id;
     $all[0]['integral_id'] = $jfid;
     //贷款额度积分69
     $all[1]['num'] = round($num*0.69,2);
     $all[1]['status'] = 3;
     $all[1]['user_id'] = $id;
     $all[1]['integral_id'] = $jfid;
     //公司证券（冻结部分）10
     $all[2]['num'] = round($num*0.10,2);
     $all[2]['status'] = 2;
     $all[2]['user_id'] = $id;
     $all[2]['integral_id'] = $jfid;
     //税收积分6
     $all[3]['num'] = round($num*0.06,2);
     $all[3]['status'] = 6;
     $all[3]['user_id'] = $id;
     $all[3]['integral_id'] = $jfid;
     $model = new app\api\model\Integraldetailed;
     $model->saveAll($all);
    return true;
}

//二维码生成
//$id = 用户id
function ewm($id){
    $url = "{:url('api/user/useradd')}" . "?user_id=" . $id;
    $aa = str_replace('\\','/',$_SERVER['DOCUMENT_ROOT']);
    include $_SERVER['DOCUMENT_ROOT'] . "/phpqrcode/phpqrcode.php"; //引入PHP QR库文件
    $value = $url;
    //保存地址
    $time = date('YmdHis') . rand(10000,99999);
    $imgname = '\upload\\userewm\\' . $time . '.jpg';
    $address = $_SERVER['DOCUMENT_ROOT'] . $imgname;
    //控制二维码容错率，不同的参数表示二维码可被覆盖的区域百分比
    $errorCorrectionLevel = "L";
    //控制生成图片的大小
    $matrixPointSize = "5";
    $margin = '5';
    model('user')->save(['ewmimages'=>$imgname],['id'=>$id]);
    $a = \QRcode::png($value, $address, $errorCorrectionLevel, $matrixPointSize,$margin);
    return true;
}
function fh($code,$status,$message,$data = []){
    return json_encode([
        'code' => $code,
        'status' => $status,
        'message' => $message,
        'data' => $data,
    ],JSON_UNESCAPED_UNICODE);
}
function jm($password){
    return md5($password . md5($password) . 'ysh');
}
/**
 * Excel导出，TODO 可继续优化
 *
 * @param array  $datas      导出数据，格式['A1' => 'XXXX公司报表', 'B1' => '序号']
 * @param string $fileName   导出文件名称
 * @param array  $options    操作选项，例如：
 *                           bool   print       设置打印格式
 *                           string freezePane  锁定行数，例如表头为第一行，则锁定表头输入A2
 *                           array  setARGB     设置背景色，例如['A1', 'C1']
 *                           array  setWidth    设置宽度，例如['A' => 30, 'C' => 20]
 *                           bool   setBorder   设置单元格边框
 *                           array  mergeCells  设置合并单元格，例如['A1:J1' => 'A1:J1']
 *                           array  formula     设置公式，例如['F2' => '=IF(D2>0,E42/D2,0)']
 *                           array  format      设置格式，整列设置，例如['A' => 'General']
 *                           array  alignCenter 设置居中样式，例如['A1', 'A2']
 *                           array  bold        设置加粗样式，例如['A1', 'A2']
 *                           string savePath    保存路径，设置后则文件保存到服务器，不通过浏览器下载
 */
function exportExcel($datas,$fileName = '',$options = [])
{
    try {
        if (empty($datas)) {
            return false;
        }
        //return 123;
        set_time_limit(0);
        /** @var Spreadsheet $objSpreadsheet */
//        $objSpreadsheet = app(Spreadsheet::class);
        $objSpreadsheet = new Spreadsheet();
        //return pr($objSpreadsheet);
        /* 设置默认文字居左，上下居中 */
        $styleArray = [
            'alignment' => [
                'horizontal' => Alignment::HORIZONTAL_LEFT,
                'vertical'   => Alignment::VERTICAL_CENTER,
            ],
        ];
        $objSpreadsheet->getDefaultStyle()->applyFromArray($styleArray);
        /* 设置Excel Sheet */
        $activeSheet = $objSpreadsheet->setActiveSheetIndex(0);

        /* 打印设置 */
        if (isset($options['print']) && $options['print']) {
            /* 设置打印为A4效果 */
            $activeSheet->getPageSetup()->setPaperSize(PageSetup:: PAPERSIZE_A4);
            /* 设置打印时边距 */
            $pValue = 1 / 2.54;
            $activeSheet->getPageMargins()->setTop($pValue / 2);
            $activeSheet->getPageMargins()->setBottom($pValue * 2);
            $activeSheet->getPageMargins()->setLeft($pValue / 2);
            $activeSheet->getPageMargins()->setRight($pValue / 2);
        }

        /* 行数据处理 */
        foreach ($datas as $sKey => $sItem) {
            /* 默认文本格式 */
            $pDataType = DataType::TYPE_STRING;

            /* 设置单元格格式 */
            if (isset($options['format']) && !empty($options['format'])) {
                $colRow = Coordinate::coordinateFromString($sKey);

                /* 存在该列格式并且有特殊格式 */
                if (isset($options['format'][$colRow[0]]) &&
                    NumberFormat::FORMAT_GENERAL != $options['format'][$colRow[0]]) {
                    $activeSheet->getStyle($sKey)->getNumberFormat()
                        ->setFormatCode($options['format'][$colRow[0]]);

                    if (false !== strpos($options['format'][$colRow[0]], '0.00') &&
                        is_numeric(str_replace(['￥', ','], '', $sItem))) {
                        /* 数字格式转换为数字单元格 */
                        $pDataType = DataType::TYPE_NUMERIC;
                        $sItem     = str_replace(['￥', ','], '', $sItem);
                    }
                } elseif (is_int($sItem)) {
                    $pDataType = DataType::TYPE_NUMERIC;
                }
            }

            $activeSheet->setCellValueExplicit($sKey, $sItem, $pDataType);

            /* 存在:形式的合并行列，列入A1:B2，则对应合并 */
            if (false !== strstr($sKey, ":")) {
                $options['mergeCells'][$sKey] = $sKey;
            }
        }

        unset($datas);

        /* 设置锁定行 */
        if (isset($options['freezePane']) && !empty($options['freezePane'])) {
            $activeSheet->freezePane($options['freezePane']);
            unset($options['freezePane']);
        }

        /* 设置宽度 */
        if (isset($options['setWidth']) && !empty($options['setWidth'])) {
            foreach ($options['setWidth'] as $swKey => $swItem) {
                $activeSheet->getColumnDimension($swKey)->setWidth($swItem);
            }

            unset($options['setWidth']);
        }

        /* 设置背景色 */
        if (isset($options['setARGB']) && !empty($options['setARGB'])) {
            foreach ($options['setARGB'] as $sItem) {
                $activeSheet->getStyle($sItem)
                    ->getFill()->setFillType(Fill::FILL_SOLID)
                    ->getStartColor()->setARGB(Color::COLOR_YELLOW);
            }

            unset($options['setARGB']);
        }

        /* 设置公式 */
        if (isset($options['formula']) && !empty($options['formula'])) {
            foreach ($options['formula'] as $fKey => $fItem) {
                $activeSheet->setCellValue($fKey, $fItem);
            }

            unset($options['formula']);
        }

        /* 合并行列处理 */
        if (isset($options['mergeCells']) && !empty($options['mergeCells'])) {
            $activeSheet->setMergeCells($options['mergeCells']);
            unset($options['mergeCells']);
        }

        /* 设置居中 */
        if (isset($options['alignCenter']) && !empty($options['alignCenter'])) {
            $styleArray = [
                'alignment' => [
                    'horizontal' => Alignment::HORIZONTAL_CENTER,
                    'vertical'   => Alignment::VERTICAL_CENTER,
                ],
            ];

            foreach ($options['alignCenter'] as $acItem) {
                $activeSheet->getStyle($acItem)->applyFromArray($styleArray);
            }

            unset($options['alignCenter']);
        }

        /* 设置加粗 */
        if (isset($options['bold']) && !empty($options['bold'])) {
            foreach ($options['bold'] as $bItem) {
                $activeSheet->getStyle($bItem)->getFont()->setBold(true);
            }

            unset($options['bold']);
        }

        /* 设置单元格边框，整个表格设置即可，必须在数据填充后才可以获取到最大行列 */
        if (isset($options['setBorder']) && $options['setBorder']) {
            $border    = [
                'borders' => [
                    'allBorders' => [
                        'borderStyle' => Border::BORDER_THIN, // 设置border样式
                        'color'       => ['argb' => 'FF000000'], // 设置border颜色
                    ],
                ],
            ];
            $setBorder = 'A1:' . $activeSheet->getHighestColumn() . $activeSheet->getHighestRow();
            $activeSheet->getStyle($setBorder)->applyFromArray($border);
            unset($options['setBorder']);
        }

        $fileName = !empty($fileName) ? $fileName : (date('YmdHis') . '.xlsx');

        if (!isset($options['savePath'])) {
            /* 直接导出Excel，无需保存到本地，输出07Excel文件 */
            header('Content-Type: application/vnd.openxmlformats-officedocument.spreadsheetml.sheet');
            header(
                "Content-Disposition:attachment;filename=" . iconv(
                    "utf-8", "GB2312//TRANSLIT", $fileName
                )
            );
            header('Cache-Control: max-age=0');//禁止缓存
            $savePath = 'php://output';
        } else {
            $savePath = $options['savePath'];
        }
        ob_clean();
        ob_start();
        $objWriter = IOFactory::createWriter($objSpreadsheet, 'Xlsx');
        $pp = $objWriter->save($savePath);
        /* 释放内存 */
        $objSpreadsheet->disconnectWorksheets();
        unset($objSpreadsheet);
        ob_end_flush();
        return true;
    } catch (Exception $e) {
        return $e->getMessage();
    }
}
/**
* send http request
* @param  array $rq http请求信息
*                   url        : 请求的url地址
*                   method     : 请求方法，'get', 'post', 'put', 'delete', 'head'
*                   data       : 请求数据，如有设置，则method为post
*                   header     : 需要设置的http头部
*                   host       : 请求头部host
*                   timeout    : 请求超时时间
*                   cert       : ca文件路径
*                   ssl_version: SSL版本号
* @return string    http请求响应
*/
if (!function_exists('curl_send')) {  
    function curl_send($rq) {
        $curlHandle = curl_init();
        curl_setopt($curlHandle, CURLOPT_URL, $rq['url']);
        switch (true) {
            case isset($rq['method']) && in_array(strtolower($rq['method']), array('get', 'post', 'put', 'delete', 'head')):
                $method = strtoupper($rq['method']);
                break;
            case isset($rq['data']):
                $method = 'POST';
                break;
            default:
                $method = 'GET';
        }
        $header = isset($rq['header']) ? $rq['header'] : array();
        $header[] = 'Method:' . $method;
        
        $header[] = "User-Agent:Mozilla/4.0 (compatible; MSIE 7.0; Windows NT 6.0; SLCC1; .NET CLR 2.0.50727; .NET CLR 3.0.04506; .NET CLR 3.5.21022; .NET CLR 1.0.3705; .NET CLR 1.1.4322)";
        isset($rq['host']) && $header[] = 'Host:'.$rq['host'];
        curl_setopt($curlHandle, CURLOPT_HTTPHEADER, $header);
        curl_setopt($curlHandle, CURLOPT_RETURNTRANSFER, 1);
        curl_setopt($curlHandle, CURLOPT_CUSTOMREQUEST, $method);
        isset($rq['timeout']) && curl_setopt($curlHandle, CURLOPT_TIMEOUT, $rq['timeout']);
        isset($rq['data']) && in_array($method, array('POST', 'PUT')) && curl_setopt($curlHandle, CURLOPT_POSTFIELDS, $rq['data']);
        
        $ssl = substr($rq['url'], 0, 8) == "https://" ? true : false;
        if( isset($rq['cert'])){
            curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER,true);
            curl_setopt($curlHandle, CURLOPT_CAINFO, $rq['cert']);
            curl_setopt($curlHandle, CURLOPT_SSL_VERIFYHOST,2);
            if (isset($rq['ssl_version'])) {
                curl_setopt($curlHandle, CURLOPT_SSLVERSION, $rq['ssl_version']);
            } else {
                curl_setopt($curlHandle, CURLOPT_SSLVERSION, 4);
            }
        }else if( $ssl ){
            curl_setopt($curlHandle, CURLOPT_SSL_VERIFYPEER,false);   //true any ca
            curl_setopt($curlHandle, CURLOPT_SSL_VERIFYHOST,2);       //check only host
            if (isset($rq['ssl_version'])) {
                curl_setopt($curlHandle, CURLOPT_SSLVERSION, $rq['ssl_version']);
            } else {
                curl_setopt($curlHandle, CURLOPT_SSLVERSION, 4);
            }
        }
        $return['content'] = curl_exec($curlHandle);
        $return['result'] = curl_getinfo($curlHandle);
        curl_close($curlHandle);
        return $return;
    }
}


/**
 * 获取随机字符串
 * @param number $length 长度
 * @param string $type 类型
 * @param number $convert 转换大小写
 * @return string 随机字符串
 */
function random($length = 6, $type = 'string', $convert = 0) {
    $config = array(
        'number' => '1234567890',
        'letter' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ',
        'string' => 'abcdefghjkmnpqrstuvwxyzABCDEFGHJKMNPQRSTUVWXYZ23456789',
        'all' => 'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890'
    );

    if (!isset($config[$type]))
        $type = 'string';
    $string = $config[$type];

    $code = '';
    $strlen = strlen($string) - 1;
    for ($i = 0; $i < $length; $i++) {
        $code .= $string{mt_rand(0, $strlen)};
    }
    if (!empty($convert)) {
        $code = ($convert > 0) ? strtoupper($code) : strtolower($code);
    }
    return $code;
}
